# coding=utf-8
# 申思远
#20190417
# 前端页面权限测试

from sqlalchemy import create_engine,func
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sanic import response
from router.router import *
from conf import *

engine = create_engine("mysql+pymysql://root:123123@39.98.207.118:3306/zxzldb_test?charset=utf8",\
                       pool_size=10,max_overflow=3,echo_pool=True)
Session = sessionmaker(bind=engine)  #订制会话
Base =automap_base()
Base.prepare(engine,reflect=True)

print(engine)


@app.middleware('response')#用于处理跨域的问题，只要是响应，都会经过此中间件，加上用于跨域的头
async def handle_reponse_wx(request,response):
    response.headers["Access-Control-Allow-Origin"] = '*'
    response.headers["Access-Control-Allow-Methods"] = "POST,GET,OPTIONS"
    response.headers["Access-Control-Expose-Headers"] = "Set-Cookie,token"
    response.headers["Access-Control-Allow-Headers"] = "Set-Cookie,token"
    response.headers["Access-Control-Allow-Credentials"] = "true"

@app.route('/hello')
async def handle_hello(request):
    return response.json({"hello":"world"})

@app.route('/readuser')
async def readuser(request):
    sess = Session()
    dev = Base.classes.user
    res=sess.query(dev.user_name,dev.passwd,dev.tel).all()
    sess.close()
    print('res:',res)
    return response.json({"data":res})

@app.route('/adduser',methods=['POST'])
async def adduser(request):
    print(request.form)
    sess=Session()
    User=Base.classes.user
    Role = Base.classes.role
    UserRole=Base.classes.user_role
    username=request.form.get('username')
    passwd=request.form.get('passwd')
    tel=request.form.get('tel')
    privilage=request.form.get('privilage')
    sess.add(User(user_name=username,passwd=passwd,tel=tel,is_vaild=1))
    sess.commit()
    iduser=sess.query(User.iduser).filter_by(tel=tel).first()[0]
    idrole=sess.query(Role.idrole).filter_by(role=privilage).first()[0]
    print(iduser,idrole)
    sess.add(UserRole(iduser=iduser,idrole=idrole))
    sess.commit()
    sess.close()
    return response.json({"code":"sucess"})

@app.route('/addpage',methods=['POST'])
async def addpage(request):
    print(request.form)
    sess = Session()
    Page = Base.classes.page
    name = request.form.get('name')
    parentpage = request.form.get('parentpage')
    if sess.query(Page.idpage).filter_by(name=name).first():
        return response.json({"code":"页面已存在，请检查"})
    #try:
    parent_id=0
    if parentpage:
        parent_id = sess.query(Page.idpage).filter_by(name=parentpage).first()[0]#查找当前页面的父页面id
        if not parent_id:
            return response.json({"code":"父页面不存在，请检查"})
    sess.add(Page(name=name, parent_id=parent_id,child_id='0'))#讲父页面id写入当前数据中
    sess.commit()
    idpage = sess.query(Page.idpage).filter_by(name=name).first()[0]#查找当前要插入页面的id作为子id插入到父页面中
    obj=sess.query(Page.child_id).filter_by(name=parentpage)

    if parent_id:
        if obj.first()[0] == '0':#如果页面中存在child_id为‘0’，则说明当前页面不存在子页面，替换其中的0即可
            idpage=str(idpage)#查找出父页面中存的子id并做拼接

        else:
            idpage=obj.first()[0]+' '+ str(idpage)
        print("子页面",idpage)
        obj.update({'child_id':idpage})#将拼接好的id更新到字段中
        sess.commit()
    sess.close()
    # except:
    #     print("数据存在")
    #     sess.rollback()
    return response.json({"code":"success"})


@app.route('/addrole',methods=['POST'])
async def addpage(request):
    print(request.form)
    sess = Session()
    Role = Base.classes.role
    Page = Base.classes.page
    RolePage=Base.classes.role_page
    role = request.form.get('role')
    rolename = request.form.get('name')
    page = request.form.get('page').split()
    sess.add(Role(role=role,role_name=rolename))
    sess.commit()
    idrole=sess.query(Role.idrole).filter_by(role=role).first()[0]
    if page:
        for i in page:
            idpage = sess.query(Page.idpage).filter_by(name=i).first()[0]
            sess.add(RolePage(idrole=idrole,idpage=idpage))
    else:
        sess.add(RolePage(idrole=idrole, idpage=''))
    sess.commit()
    sess.close()
    return response.json({"code":"success"})

def searchroot(page):
    temp=[]
    temppage=page.copy()
    for i,v in temppage.items():
        if v['parent_id'] not in temppage.keys():
            temp.append(i)
    return set(temp)



def read(node,a):#node是一个实例（一个页面或者子页面或者子元素）
    temp={}
    temp['name']=node['name']
    if node['child_id']!='0':
        #print(node['child_id'])
        m=node['child_id'].split()
        temp['children']=[]
        for i in m:
            temp['children'].append(read(a[str(i)],a))
    return temp

@app.route('/getprivilage/<tel>',methods=['GET'])
async def getprivilate(request,tel):
    # 查询当前用户的权限
    sess = Session()
    User = Base.classes.user
    Role = Base.classes.role
    UserRole = Base.classes.user_role
    RolePage = Base.classes.role_page
    Page=Base.classes.page
    iduser = sess.query(User.iduser).filter_by(tel=tel).first()[0]
    idrole=sess.query(UserRole.idrole).filter_by(iduser=iduser).first()[0]
    res = sess.query(Role.role,Role.role_name).filter_by(idrole=idrole).first()
    idpage=sess.query(RolePage.idpage).filter_by(idrole=idrole).all()
    idpage=[i[0] for i in idpage]
    print("当前用户的权限：",res)
    print("当前用户可访问页面的id：",idpage)
    page={}
    for i in idpage:
        res=sess.query(Page.name,Page.parent_id,Page.child_id).filter_by(idpage=int(i)).first()
        temp={}
        temp['name'] = res[0]
        temp['parent_id']=res[1]
        temp['child_id']=res[2]
        page[str(i)] = temp

    sess.close()

    #privilate=page
    #print("全部节点",page)
    #print("查找出来的根节点",searchroot(page))
    pageRootList=searchroot(page)

    privilate=[]
    for i in pageRootList:
        privilate.append(read(page[i],page))
    # data=[]
    # data.append(privilate)
    print("当前用户的权限页面",privilate)
    return response.json({'code':0,'message':'获取权限成功','data':privilate})

@app.route('/login',methods=['GET','POST'])
async def login(request):
    return response.json({"code":0,'message':"登录成功",'data':{'token':'iamghltokenceshi'}})


if __name__=="__main__":
    app.run(host=WEB_HOSTNAME,port=WEB_PORT,workers=1,auto_reload=True)